package com.sky.chapter2.Unsafe;

/**
 * @author : wushikai
 * <p>
 * date : 2021-03-26
 * 很容易想到这段代码的运行结果可能为(1,0)、(0,1)或(1,1)，因为线程one可以在线程two开始之前就执行完了，
 * 也可能线程two在线程one开始之前就执行完了，甚至有可能二者的指令是同时或交替执行的。
 * 然而，这段代码的执行结果也可能是(0,0)
 */
public class PossibleReordering {

    int x = 0, y = 0;
    int a = 0, b = 0;

    public void test() throws InterruptedException {


        Thread one = new Thread(() -> {

            a = 1;
            x = b;

        });

        Thread two = new Thread(() -> {

            b = 1;
            y = a;

        });


        one.start();
        two.start();
        one.join();
        two.join();


         System.out.println("(" + x + "," + y + ")");

    }


    public static void main(String[] args) throws InterruptedException {

        for (int i = 0; i < 100; i++) {
            PossibleReordering obj = new PossibleReordering();
            obj.test();
            if (obj.x == 0 && obj.y == 0) {
                System.out.println("(" + obj.x + "," + obj.y + ")");
            }

        }

    }


}